<template>
    <div class="content-box">
      <div ref="searchBox" class="search-box flex" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="100px"
        >
        <el-form-item
            label="下游产品"
            prop="productIds"
          >
            <el-select
              v-model="queryParams.productIds"
              multiple
              collapse-tags
              clearable
              filterable
              placeholder="请选择"
              style="width: 240px; margin-right: 20px"
            >
              <el-option
                v-for="(item, index) in downProductOptionList"
                :key="index"
                :label="item.productName"
                :value="item.id"
              ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item
          label="测试状态"
          style="margin-right: 20px"
          prop="testStatus"
        >
          <el-select
            v-model="queryParams.testStatus"
            clearable
            filterable
            placeholder="请选择"
            style="width: 240px; margin-right: 20px"
          >
            <el-option
              v-for="(item, index) in testStatusOption"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              plain
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
  
      <div class="table-box">
        <el-row :gutter="10" class="mb8">
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="handleQuery"
            :columns="columns"
          ></right-toolbar>
        </el-row>
        <el-table
          v-sticky-header
          ref="table"
          v-loading="loading"
          :data="dataList"
        >
          <template v-for="(item,index) in columns">
            <el-table-column
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :width="getColumnWidth(index)"
              :fixed="item.fixed"
              :sortable="item.sortable ? item.sortable : false"
              :show-overflow-tooltip="item.showTooltip"
              v-if="item.visible"
              align="center"
            >
               <template slot-scope="scope">
                  <!-- 测试状态单独处理 -->
                  <span v-if="item.prop == 'testStatus'">
                    <el-tag :type="scope.row[item.prop]?'success':'danger'">
                      {{ ArrayFormatObj(testStatusOption)[scope.row[item.prop]]}}
                    </el-tag>
                  </span>
                  <!-- 测试方式单独处理 -->
                  <span v-else-if="item.prop == 'testType'">
                    <span>
                      {{ ArrayFormatObj(testTypeOption)[scope.row[item.prop]]}}
                    </span>
                  </span>
                   <!-- 风险等级单独处理 -->
                   <span v-else-if="item.prop == 'riskNum'">
                    <el-rate 
                     v-model="scope.row.riskNum" 
                     :texts="['低风险','中等风险','重点关注','高风险']"
                     @change="riskNumChange(scope.row)"
                     :max="4"
                     ></el-rate>
                     <span :style="{color: riskNumTxtColor(scope.row.riskNum)}">{{ riskNumTxt(scope.row.riskNum) }}</span>
                  </span>
                  <span v-else>
                    {{ scope.row[item.prop] }}
                  </span>
               </template>
            </el-table-column>
          </template>
        </el-table>
        <!-- 使用分页插件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page-sizes="[10, 50, 100, 200, 500]"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
  </template>
  
  <script>
  import tableStickyMixins from "@/mixins/tableStickyMixins";
  import { mapGetters } from "vuex";
  import { getDownProductList } from "@/api/business/productManagement";

  import {
    queryAutoAbroadTestTaskByPage,
    setRiskNum
  } from "@/api/autoTest/onlineProduct";
  
  export default {
    // 定义名字用于标识该组件是否被keep-alive缓存
    name: "OnlineProduct",
    data() {
      return {
        // 数据列表
        dataList: [],
        // 下游产品筛选项
        downProductOptionList: [],
        // 总条数
        total: 0,
        // 查询参数
        queryParams: {
          pageIndex: 1,
          pageSize: 10,
        },
        loading: false,
        // 表格列信息
        columns: [
         {label: `产品名称`,prop: "productName",visible: true,pcWidth: 'auto',mobileWidth: 100,fixed: null,showTooltip: true,},
         {label: `测试状态`,prop: "testStatus",visible: true,pcWidth: 180,mobileWidth: 100,fixed: null,showTooltip: true,},
         {label: `测试方式`,prop: "testType",visible: true,pcWidth: 'auto',mobileWidth: 100,fixed: null,showTooltip: true,},
         {label: `手机号`,prop: "testPhone",visible: true,pcWidth: 'auto',mobileWidth: 100,fixed: null,showTooltip: true,},
         {label: `风险等级`,prop: "riskNum",visible: true,pcWidth: 'auto',mobileWidth: 100,fixed: null,showTooltip: true,},
         {label: `测试时间`,prop: "testTime",visible: true,pcWidth: 'auto',mobileWidth: 100,fixed: null,showTooltip: true,},
        ],
        // 显示搜索栏
        showSearch: true,
        // 测试状态筛选项
        testStatusOption:[
          {label:'未测试',value:0},
          {label:'已测试',value:1}
        ],
        // 测试方式筛选项
        testTypeOption:[
          {label:'未测试',value:0},
          {label:'每天',value:1},
          {label:'间隔分钟',value:2},
          {label:'间隔小时',value:3}
        ],
        
      };
    },
    mixins: [tableStickyMixins],
    watch: {
      columns: {
        handler() {
          this.updateTableHeight();
        },
        deep: true,
      },
    },
    created() {
      this.getProductList()
      this.getList();
    },
    computed: {
      ...mapGetters(["sidebar", "device"]),
      // 计算当前列元素在所处环境的宽度
      getColumnWidth() {
        return (index) => {
          return this.isMobile
            ? this.columns[index].mobileWidth
            : this?.sidebar?.opened
            ? this.columns[index].pcWidth - this.slightWidth
            : this.columns[index].pcWidth + 17;
        };
      },
      // 将数组转换为对象形式
      ArrayFormatObj:()=>{
         return (arr)=>{
           return arr.reduce((pre, cur)=>{
             pre[cur.value] = cur.label;
             return pre;
           },{})
         }
      },
      // 风险等级值文本
      riskNumTxt(){
        return (riskNum)=>{
           switch (riskNum) {
            case 1:
              return '低风险';
            case 2:
              return '中等风险';
            case 3:
              return '重点关注';
            case 4:
              return '高风险';
            default:
              return '未知';
          }
        }
      },
      // 风险等级值文本颜色
      riskNumTxtColor(){
        return (riskNum)=>{
           switch (riskNum) {
            case 1:
              return '#434343';
            case 2:
              return '#d4b106';
            case 3:
              return '#d46b08';
            case 4:
              return '#cf1322';
            default:
              return '#08979c';
          }
        }
      }
    },
    methods: {
      // 获取产品筛选项列表
      getProductList(){
        // 获取下游产品列表
        getDownProductList().then((res) => {
          this.downProductOptionList = res.data;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.$set(this.queryParams, "pageIndex", 1);
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        // 完全重置到初始状态
        this.$set(this, "queryParams", {
          pageIndex: 1,
          pageSize: 10,
        });
        this.getList();
      },
      // 风险等级修改后的回调
      riskNumChange(row){
        setRiskNum({
          id:row?.id,
          riskNum:row?.riskNum - 1, // 后台风险等级是从0开始的，需要-1
        }).then(res=>{
          if(res.code == 200){
            this.$message.success("风险等级修改成功");
          }
          // 重新刷新数据
          this.getList();
        }).catch(err=>{
          // 重新刷新数据
          this.getList();
        })
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        queryAutoAbroadTestTaskByPage(this.queryParams).then((response) => {
          this.dataList = response?.data?.list?.map(pre=>({...pre,riskNum:pre?.riskNum !=null?pre?.riskNum +1 :null}))
          this.total = response?.data?.total;
          this.loading = false;
        }).catch((err) => {
          setTimeout(() => {// 延迟2s后自动取消加载状态
            this.loading = false;
          }, 2000);
        })
      },
      // 修改表格高度触发回调
      updateTableHeight() {
        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });
      },

    },
  };
  </script>
  
  <style scoped lang="scss">
  .title {
    font-size: 20px;
    color: #333333;
    font-weight: 500;
  }
  .search-box {
    margin: 0 0 20px;
    padding: 20px 20px 0;
    background: #fff;
    align-items: flex-start;
    border-radius: 6px;
  }
  .search-area {
    position: absolute;
    right: 20px;
  }
  .el-form-item__content {
    flex: 1;
    line-height: 40px;
    position: relative;
    font-size: 14px;
    min-width: 0;
  }
  ::v-deep .el-dialog__body {
    border-top: 1px solid #dfe6ec;
    border-bottom: 1px solid #dfe6ec;
  }
  .el-table {
    // 滚动条加粗
    --scrollbar-height: 9px;
  }
  </style>
  